package com.webserver_v6.core;

import com.webserver_v6.annotation.Controller;
import com.webserver_v6.annotation.RequestMapping;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Method;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;

/**
 * 该类用于维护请求路径与业务处理方法的对应关系
 */
public class HandlerMapping {

    private static Map<String, Method>mapping = new HashMap<>();

    static {
        initMapping();
    }
    private static void initMapping(){
        //定位类加载路径
        try {
            File rootDir = new File(HandlerMapping.class.getClassLoader()
            .getResource(".").toURI());

            File dir = new File(rootDir, "com/webserver_v6/controller");
            File[] subs = dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.getName().endsWith(".class");
                }
            });
            for (File sub:subs){
                String className = sub.getName().replace(".class","");
                Class cls = Class.forName("com.webserver_v6.controller."+className);
                if (cls.isAnnotationPresent(Controller.class)){
                    Method[] methods = cls.getDeclaredMethods();
                    for (Method method:methods){
                        if (method.isAnnotationPresent(RequestMapping.class)){
                            RequestMapping rm = method.getAnnotation(RequestMapping.class);
                            String value = rm.value();
                            mapping.put(value,method);
                        }
                    }
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public static Method getMethod(String uri){
        return mapping.get(uri);
    }
}
